package guojin.sqlsession;

import guojin.config.BoundSql;
import guojin.pojo.Configeration;
import guojin.pojo.MappedStatement;
import guojin.utils.GenericTokenParser;
import guojin.utils.ParameterMapping;
import guojin.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author haoge
 * @version $Id simpleExecutor.java, v 0.1 2021-06-12 22:49 haoge Exp $$
 */
public class SimpleExecutor implements Executor {

    @Override
    public <T> List<T> query(Configeration configeration, MappedStatement mappedStatement, Object... paraes) throws Exception {
        //获取连接
        Connection connection = configeration.getDataSource().getConnection();
        //获取sql
        String sql = mappedStatement.getSql();
        //转化sql
        BoundSql boundSql = getBoundSql(sql);
        //获取预处理对象PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //设置参数
        List<ParameterMapping> parameterMappinglists = boundSql.getLists();
        //获取到参数的全路径
        String paramterType = mappedStatement.getParamterType();
        Class<?> classTypeClass = getClassType(paramterType);

        for (int i = 0; i < parameterMappinglists.size(); i++) {
            ParameterMapping parameterMapping = parameterMappinglists.get(i);
            //#{id} 里面的id值
            String content = parameterMapping.getContent();
            Field declaredField = classTypeClass.getDeclaredField(content);
            //暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(paraes[0]);
            preparedStatement.setObject(i + 1, o);

        }

        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();


        //结果封装结果集
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        ArrayList<Object> objects = new ArrayList<>();

        // 6. 封装返回结果集
        while (resultSet.next()) {
            Object o = resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {

                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);


            }
            objects.add(o);

        }
        return (List<T>) objects;

    }

    @Override
    public int  insert(Configeration configeration, MappedStatement mappedStatement, Object... paraes) throws Exception {
        //获取连接
        Connection connection = configeration.getDataSource().getConnection();
        //获取sql
        String sql = mappedStatement.getSql();
        //转化sql
        BoundSql boundSql = getBoundSql(sql);
        //获取预处理对象PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //设置参数
        List<ParameterMapping> parameterMappinglists = boundSql.getLists();
        //获取到参数的全路径
        String paramterType = mappedStatement.getParamterType();
        Class<?> classTypeClass = getClassType(paramterType);

        for (int i = 0; i < parameterMappinglists.size(); i++) {
            ParameterMapping parameterMapping = parameterMappinglists.get(i);
            //#{id} 里面的id值
            String content = parameterMapping.getContent();
            Field declaredField = classTypeClass.getDeclaredField(content);
            //暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(paraes[0]);
            preparedStatement.setObject(i + 1, o);

        }

        //执行sql
        int i1 = preparedStatement.executeUpdate();






        return  i1;

    }


    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType != null) {
            Class<?> aClass = Class.forName(paramterType);
            return aClass;
        }
        return null;
    }


    //将#{}使用？进行迭代 2解析#{}里的值
    private BoundSql getBoundSql(String sql) {

        //标记处理器
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);    //解析后的sql
        String parseSql = genericTokenParser.parse(sql);
        //解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parseSql,parameterMappings);
        return boundSql;
    }





}
